import React, { useEffect, useState } from 'react';
import { Form, Input, Modal, Select, Spin,InputNumber} from 'antd';
import {searchsteaList} from '../service'
import { set } from 'numeral';

const { Option } = Select;
const FormItem = Form.Item;

const CreateForm = props => {
  const [classvalue, setclassvalue] = useState('')
  const [teachdata, setteachdata] = useState([])
  const [classfetch, setclassfetch] = useState(false)
  const [lastFetchId, setlastFetchId] = useState(0)
  // 经 Form.useForm() 创建的 form 控制实例，不提供时会自动创建
  const [form] = Form.useForm();
  // 把父组件方法和属性传递过来到子组件
  const { current,modalVisible, onSubmit, onCancel } = props;
  console.log(current)
    // 监听编辑传过来的数据渲染上
    useEffect(() => {
      if (form && !modalVisible) {
        // 每一次刷新都重置一次
        form.resetFields();
      }
      console.log(props, current, form, props.current)
    }, [props.modalVisible]);
  useEffect(() => {
    // 如果有props.current的值才会执行这个
    if (current) {
      form.setFieldsValue({
        ...current,
      });
      // setclassvalue(current.admin_name)
      fetchUser(current.student_number || current.teacher_name )
      console.log(current, form, props.current)
    }
  }, [props.current]);
  // 点击确定的增加方法，里面调用了父组件的方法 触发表单验证收集value值
  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    console.log(form,fieldsValue)
    if (fieldsValue.admin_id) {
      // fieldsValue.admin_id=fieldsValue.admin_id.value
    }
    console.log(fieldsValue)
    // 利用父组件传递过来的方法，顺便传此子组件的值。进行调用
    onSubmit(fieldsValue);
  };

  const fetchUser =async value => {
    console.log('fetching user', value);
    setlastFetchId(lastFetchId + 1);
    const fetchId = lastFetchId;
    setteachdata([])
    setclassfetch(true)
   const datas= await searchsteaList({name:value})
         if (fetchId !== lastFetchId) {
          // for fetch callback order
          return;
        }
        setteachdata(datas.data)

  
  };
  const handleChange = value => {
    console.log(value)
  };
  return (
    // 弹出对话框 destroyOnClose关闭时销毁model子元素 //onok点击确定回调
    <Modal
      destroyOnClose
      title={current ? '班级编辑' : '班级添加'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >
      <Form form={form}>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="班级代码"
          name="class_code"
          rules={[{ required: true, message: 'Please input your message!' }]}

        >
          <Input placeholder="请输入" />
        </FormItem>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="班级年级"
          name="grade"
          rules={[{ required: true, message: 'Please input your message!' }]}

        >
          <InputNumber min={1} 
                         defaultValue={3} 
                         formatter={value => `${value}`}
                         parser={value => value.replace(/[^\d]/g,'')}
                         precision={0}/>
        </FormItem>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="班级名称"
          name="class_name"
          rules={[{ required: true, message: 'Please input your message!' }]}
        >
          <Input placeholder="请输入" />
        </FormItem>
        <FormItem
         help='可搜索工号或者姓名'
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="负责教师"
          name="admin_id"
          rules={[{ required: true, message: 'Please input your message!' }]}
          shouldUpdate={(prevValues, curValues) => prevValues.additional !== curValues.additional}

        >
            <Select
                  showSearch
                  defaultValue={current ? current.teacher_name : ''}
                  value={classvalue}
                  placeholder="可输入工号或者姓名"
                  notFoundContent={classfetch ? <Spin size="small" /> : null}
                  filterOption={false}
                  onSearch={fetchUser}
                  onChange={handleChange}
                  style={{ width: '100%' }}
                >
                  {teachdata.map(d => (
                    <Option key={d.id} value={d.id}>{d.name}</Option>
                  ))}
                </Select>

              

        </FormItem>
      
      
      </Form>
    </Modal>
  );
};

export default CreateForm;
